//
//  String+Express.swift
//  emoticonText
//
//  Created by 陈锦聪 on 16/4/5.
//  Copyright © 2016年 Coco. All rights reserved.
//

import UIKit

extension String {
    
    func emoticonTextToEmoticonAttributedString(font: UIFont) -> NSAttributedString {
        
        let pattern = "\\[.*?\\]"
        let regular = try! NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.DotMatchesLineSeparators)
        let results = regular.matchesInString(self, options: NSMatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count))
        // 替换使用let, 重新复制使用var
        let attributdString = NSMutableAttributedString(string: self)
        // 数组颠倒遍历
        for result in results.reverse() {
            let range = result.rangeAtIndex(0)
            let emoticonName = (self as NSString).substringWithRange(range)
            if let emoticon = CNEmoticonModel.emoticonNameToEmoticonModel(emoticonName) {
                let attr = emoticon.emoticonModelToAttributedString(font)
                attributdString.replaceCharactersInRange(range, withAttributedString: attr)
            }
        }
        return attributdString
    }
}